<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebRTC Video Call</title>
  <style>
    video {
      max-width: 50%;
      margin: 20px;
    }
  </style>
</head>
<body>
  <h1>WebRTC Video Call</h1>
  <video id="localVideo" autoplay muted></video>
  <video id="remoteVideo" autoplay></video>
  <script>
    const localVideo = document.getElementById('localVideo');
    const remoteVideo = document.getElementById('remoteVideo');
    const socket = new WebSocket('ws://localhost:8080');

    let localStream;
    let remoteStream;
    let peerConnection;

    async function start() {
      try {
        localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        localVideo.srcObject = localStream;

        createPeerConnection();
        localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));

        socket.onmessage = async (event) => {
          const message = JSON.parse(event.data);
          if (message.sdp) {
            await peerConnection.setRemoteDescription(new RTCSessionDescription(message));
            if (message.sdp.type === 'offer') {
              const answer = await peerConnection.createAnswer();
              await peerConnection.setLocalDescription(answer);
              socket.send(JSON.stringify({ sdp: peerConnection.localDescription }));
            }
          } else if (message.iceCandidate) {
            await peerConnection.addIceCandidate(new RTCIceCandidate(message.iceCandidate));
          }
        };

        socket.onopen = () => {
          console.log('WebSocket connection opened');
          createOffer();
        };
      } catch (err) {
        console.error('Error accessing media devices.', err);
      }
    }

    function createPeerConnection() {
      peerConnection = new RTCPeerConnection();

      peerConnection.onicecandidate = event => {
        if (event.candidate) {
          socket.send(JSON.stringify({ iceCandidate: event.candidate }));
        }
      };

      peerConnection.ontrack = event => {
        remoteStream = event.streams[0];
        remoteVideo.srcObject = remoteStream;
      };
    }

    async function createOffer() {
      const offer = await peerConnection.createOffer();
      await peerConnection.setLocalDescription(offer);
      socket.send(JSON.stringify({ sdp: peerConnection.localDescription }));
    }

    start();
  </script>
</body>
</html>